<script setup>
import { ref, onUnmounted, computed, onMounted } from 'vue'
import { ElNotification } from 'element-plus'
import { useSelectStore } from '../../store/select.js'
const selectStore = useSelectStore()
import imgUrl from '../../../src/assets/logo.jpg'
import { getBoyImage, getGirlImg } from '../../utils/defaultImg.js'
import { exportExcel } from '@renderer/utils/exportExcel'
const defaultBoy = getBoyImage()
const defaultGirl = getGirlImg()
const circleUrl = ref(imgUrl)
const name = ref('来试试吧')
const number = ref()
const sex = ref(null)
const classNum = ref(null)
const copy = (obj) => {
  let jsonTemp = JSON.stringify(obj)
  let res = JSON.parse(jsonTemp)
  return res
}
const mainOut = window.electronAPI.mainOut
//promise
const myPromise = (callback) => {
  return new Promise((resolve) => {
    callback((result) => {
      resolve(result)
    })
  })
}
// const counter = ref(0)
const intervalId = ref(null)
const startCounter = async () => {
  if (checkedCities.value.length == 0) {
    ElMessage.error('请至少选择一个班级')
    return
  }
  let classList = checkedCities.value.map((e) => e.split('班')[0])
  let obj = {
    page: 1,
    size: 2000,
    classList,
    isRandom: true
  }
  console.log('obj', obj)
  await window.electronAPI.rendererSend('page', copy(obj))
  let res = await myPromise((callback) => {
    mainOut(callback)
  })
  let {
    data: {
      data: { list }
    }
  } = res
  console.log(list)

  if (!intervalId.value) {
    intervalId.value = setInterval(() => {
      let min = 0 // 最小值
      let max = list.length // 最大值
      let randomNum = Math.floor(Math.random() * (max - min + 1)) + min
      if (list[randomNum]) {
        circleUrl.value = list[randomNum].pic
        name.value = list[randomNum].name
        number.value = list[randomNum].num
        sex.value = list[randomNum].sex
        classNum.value = list[randomNum].class
      }
    }, 50)
  }
}

const stopCounter = () => {
  if (name.value != '来试试吧') {
    ElNotification({
      title: '🎲 幸运之轮转动了 🎲',
      message: '恭喜 ' + name.value + '，你被幸运之神点中啦！准备好迎接挑战了吗？🚀',
      type: 'success',
      duration: 3000
    })
  }

  if (intervalId.value) {
    clearInterval(intervalId.value)
    intervalId.value = null
  }
}
onUnmounted(() => {
  // 页面卸载时清理定时器，这是一个好的实践
  if (intervalId.value) {
    clearInterval(intervalId.value)
  }
})
const select = async (type) => {
  //新增回答记录数据
  if (name.value == '来试试吧') return
  let time = getDateObj(new Date())
  let insertObj = {
    name: name.value,
    num: number.value,
    answerResult: type,
    callTime: `${time.year}-${time.month}-${time.day} ${time.hours}:${time.minutes}:${time.seconds}`,
    month: Number(time.month),
    day: Number(time.day),
    year: Number(time.year),
    class: classNum.value
  }
  await window.electronAPI.rendererSend('insertCall', copy(insertObj))
  await myPromise((callback) => {
    mainOut(callback)
  }).then(() => {
    if (type == 1) {
      ElNotification({
        title: '太强啦！🌟',
        message: '回答正确，不愧是你！继续保持这股劲头！',
        type: 'success',
        duration: 3000
      })
    }
    if (type == 2) {
      ElNotification({
        title: '就差一点点！🔍',
        message: '没事，继续努力，我相信你下次一定能行！看好你哦！',
        type: 'warning',
        duration: 3000
      })
    }
    if (type == 3) {
      ElNotification({
        title: '咋错了？🤔',
        message: '别灰心，再仔细想想，你一定能找到正确答案的！',
        type: 'error',
        duration: 3000
      })
    }
  })
  await getCallDetails()
}
const getDateObj = (date) => {
  let dateObj = {}
  dateObj.year = date.getFullYear()
  dateObj.month = String(date.getMonth() + 1).padStart(2, '0')
  dateObj.day = String(date.getDate()).padStart(2, '0')
  dateObj.hours = String(date.getHours()).padStart(2, '0')
  dateObj.minutes = String(date.getMinutes()).padStart(2, '0')
  dateObj.seconds = String(date.getSeconds()).padStart(2, '0')
  return dateObj
}
const save = (type) => {
  if (type == '导出') {
    handelExcel()
  } else if (type == '清空') {
    selectStore.setEmptySelect()
  }
}

const removeSelect = async (id) => {
  await window.electronAPI.rendererSend('deleteCallById', id)
  let res = await myPromise((callback) => {
    mainOut(callback)
  })
  if (res.data.success) {
    await getCallDetails().then(() => {
      ElNotification({
        title: 'Success',
        message: '移除成功',
        type: 'success',
        duration: 2000
      })
    })
  }
}
function generateRandomString(length) {
  return Math.random()
    .toString(36)
    .substring(2, 2 + length)
}

const handelExcel = async () => {
  await window.electronAPI.rendererSend('getCallDetails', 'all')
  let res = await myPromise((callback) => {
    mainOut(callback)
  })
  let {
    data: { data: list }
  } = res
  console.log(list)
  for (const item of list) {
    let ans = item.answerResult
    item.content = ans == 1 ? '回答正确' : ans == 2 ? '基本回答正确' : '回答错误'
  }
  const fields = ['class', 'name', 'num', 'content', 'callTime']
  // const headers = ['姓名', '学号', '时间', '合格状态']
  const headers = ['班级', '姓名', '学号', '回答情况', '回答时间']
  exportExcel(list, fields, headers, '学生点名情况表.xlsx')
}
const getRadomclass = (val) => {
  if (val < 50) return 1
  if (val < 100) return 2
  if (val < 150) return 3
  if (val < 200) return 4
}
// const getRadomNum = () => {
//   let min = 1 // 最小值
//   let max = 10000 // 最大值
//   let randomNum = Math.floor(Math.random() * (max - min + 1)) + min
//   return randomNum
// }
const test = () => {
  let list = []
  for (let i = 0; i < 200; ++i) {
    let classNum = getRadomclass(i)
    list.push({
      name: generateRandomString(10) + '-' + classNum,
      class: classNum,
      num: i,
      sex: i % 2 == 0 ? '男' : '女'
    })
  }
  const fields = ['class', 'name', 'num', 'sex']
  // const headers = ['姓名', '学号', '时间', '合格状态']
  const headers = ['班级', '姓名', '学号', '性别']
  exportExcel(list, fields, headers, '学生点名情况表.xlsx')
}
// test()
import { useSqliteStore } from '../../store/sqliteData.js'
const SqliteStore = useSqliteStore()

const checkAll = ref(false)
const isIndeterminate = ref(false)
const checkedCities = ref([])
const cities = computed(() => {
  return SqliteStore.getClassList().map((e) => e.class + '班')
})

const handleCheckAllChange = (val) => {
  checkedCities.value = val ? cities.value : []
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === cities.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < cities.value.length
}
onMounted(async () => {
  await getCallDetails()
})
const callList = ref([])
const getCallDetails = async () => {
  await window.electronAPI.rendererSend('getCallDetails')
  let res = await myPromise((callback) => {
    mainOut(callback)
  })
  callList.value = res.data.data
}
const getType = (num) => {
  if (num == 1) {
    return 'success'
  } else if (num == 2) {
    return 'primary'
  } else if (num == 3) {
    return 'danger'
  }
}
const getContent = (num) => {
  if (num == 1) {
    return '回答正确'
  } else if (num == 2) {
    return '回答基本正确'
  } else if (num == 3) {
    return '回答错误'
  }
}
</script>
<template>
  <div class="layout2">
    <div class="save" style="position: relative">
      <div class="top" style="height: 2rem">
        <el-button type="primary" text bg icon="Document" @click="save('导出')">导出</el-button>
        <el-button type="primary" text bg icon="Delete" @click="save('清空')">清空</el-button>
      </div>
      <!-- <el-select-v2
        v-model="value"
        :options="classOption"
        placeholder="请选择班级"
        style="width: 240px"
        multiple
      /> -->
      <!-- <el-checkbox-group v-model="checkList">
        <el-checkbox
          :label="item.label"
          :value="item.value"
          v-for="item in classOption"
          :key="item"
        />
      </el-checkbox-group> -->
      <div style="position: absolute; top: 2rem; width: 20vw">
        <el-checkbox
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
        >
          全选
        </el-checkbox>
        <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="city in cities" :key="city" :label="city" :value="city">
            {{ city }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </div>
    <div class="content">
      <div class="left">
        <div class="avatar">
          <el-image
            style="width: 30vw; height: 30vw; border-radius: 100%"
            :src="circleUrl ?? (sex == '男' ? defaultBoy : defaultGirl)"
          />
          <div class="text">{{ name }}</div>
          <div class="text">{{ number }}</div>
        </div>
        <div class="bottom">
          <div class="bottom_item">
            <el-button type="primary" size="large" :disabled="intervalId" @click="startCounter"
              >随机切换</el-button
            >
            <el-button type="success" size="large" :disabled="!intervalId" @click="stopCounter"
              >停止</el-button
            >
          </div>
          <div class="bottom_item" style="margin-bottom: 1em">
            <el-button
              :disabled="intervalId != null"
              type="success"
              size="large"
              icon="Select"
              @click="select(1)"
              >回答正确</el-button
            >
            <el-button :disabled="intervalId != null" type="primary" size="large" @click="select(2)"
              >基本回答正确</el-button
            >
            <el-button
              :disabled="intervalId != null"
              type="danger"
              size="large"
              icon="CloseBold"
              @click="select(3)"
              >回答错误</el-button
            >
          </div>
        </div>
      </div>
      <div class="right">
        <el-scrollbar height="100%">
          <el-timeline style="width: 97%; padding-left: 10px">
            <el-timeline-item
              v-for="(item, index) in callList"
              :key="index"
              :timestamp="item.callTime"
              placement="top"
              :type="getType(item.answerResult)"
            >
              <el-card>
                <div style="display: flex; justify-content: space-between">
                  <div>
                    <h4>{{ item.name }}</h4>
                    <p>{{ getContent(item.answerResult) }}</p>
                  </div>
                  <el-icon style="cursor: pointer" @click="removeSelect(item.id)"
                    ><Close
                  /></el-icon>
                </div>
              </el-card>
            </el-timeline-item>
            <el-empty
              style="height: 100%"
              v-if="callList.length == 0"
              class="empty"
              description="暂无人员信息"
            />
          </el-timeline>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
:deep(.el-scrollbar__view) {
  height: 100%;
}
:deep(.el-timeline) {
  height: 100%;
}
.bottom {
  display: flex;
  flex-direction: column;
}
.empty {
  width: 100%;
  height: 100%;
}
.save {
  // position: absolute;
  // top: 1em;
  margin-top: 20px;
}
.content {
  display: flex;
  width: 100%;
  height: 100%;
  justify-content: space-between;
  .left {
    height: 100%;
    flex: 2;
    align-content: center;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
}
.layout2 {
  margin: 0;
  padding: 0;
  border-radius: 1em;
  position: relative;
  overflow: auto;
  width: 100%;
  height: 100%;
  background-color: #fff;
  padding: 0px 20px;
  display: flex;
  flex-direction: column;
  .avatar {
    margin: 0;
    padding: 0;
    width: 100%;
    height: auto;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  .bottom_item {
    margin: 0;
    padding: 0;
    margin: 0 0 1rem 0;
    padding: 0;
    display: flex;
    width: 100%;
    justify-content: center;
  }

  .text {
    margin: 0;
    padding: 0;
    width: 700;
    font-size: 2rem;
    height: 2rem;
    line-height: 2rem;
  }
}
.right {
  margin: 0;
  padding: 0;
  position: absolute;
  right: 1em;
  width: 25%;
  overflow-y: auto;
  position: absolute;
  top: 0;
  padding: 10px;
  height: calc(100% - 20px);
}
* {
  box-sizing: border-box;
}
</style>
